<template>
  <div class="login-container">
    <!-- 全局提示悬浮窗 -->
    <div 
      class="toast" 
      :class="{ 'toast-show': showToast, 'toast-error': toastType === 'error', 'toast-success': toastType === 'success' }"
      @click="hideToast"
    >
      <div class="toast-content">
        <i :class="toastIcon"></i>
        <span>{{ toastMessage }}</span>
      </div>
      <div class="toast-progress" :style="{ width: progressWidth }"></div>
    </div>

    <!-- 背景装饰 -->
    <div class="bg-decoration"></div>
    
    <!-- 登录表单卡片 -->
    <div class="login-card">
      <div class="login-header">
        <h1>购物商城</h1>
        <p>欢迎回来，请登录您的账号</p>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-type-tabs">
        <button 
          :class="{ active: loginType === 'phone' }" 
          @click="switchLoginType('phone')"
        >
          手机号登录
        </button>
        <button 
          :class="{ active: loginType === 'email' }" 
          @click="switchLoginType('email')"
        >
          邮箱登录
        </button>
      </div>

      <!-- 手机号登录表单（手机号+密码） -->
      <form v-if="loginType === 'phone'" class="login-form">
        <div class="form-group">
          <label class="form-label">手机号</label>
          <div class="input-wrapper">
            <i class="icon-phone"></i>
            <input 
              type="tel" 
              placeholder="请输入手机号" 
              v-model="phoneForm.phone"
              @input="clearError('phone')"
            >
          </div>
          <p v-if="errors.phone" class="error-message">{{ errors.phone }}</p>
        </div>

        <div class="form-group">
          <label class="form-label">密码</label>
          <div class="input-wrapper">
            <i class="icon-lock"></i>
            <input 
              type="password" 
              placeholder="请输入密码" 
              v-model="phoneForm.password"
              @input="clearError('phonePassword')"
            >
          </div>
          <p v-if="errors.phonePassword" class="error-message">{{ errors.phonePassword }}</p>
        </div>
      </form>

      <!-- 邮箱登录表单（邮箱+验证码） -->
      <form v-if="loginType === 'email'" class="login-form">
        <div class="form-group">
          <label class="form-label">邮箱</label>
          <div class="input-wrapper">
            <i class="icon-email"></i>
            <input 
              type="email" 
              placeholder="请输入注册邮箱" 
              v-model="emailForm.email"
              @input="clearError('email')"
            >
          </div>
          <p v-if="errors.email" class="error-message">{{ errors.email }}</p>
        </div>

        <div class="form-group">
          <label class="form-label">验证码</label>
          <div class="input-with-btn">
            <div class="input-wrapper">
              <i class="icon-code"></i>
              <input 
                type="text" 
                placeholder="请输入邮箱验证码" 
                v-model="emailForm.code"
                @input="clearError('emailCode')"
              >
            </div>
            <button 
              type="button" 
              class="code-btn"
              :disabled="emailCountdown > 0"
              @click="sendEmailCaptcha"
            >
              {{ emailCountdown > 0 ? `${emailCountdown}s后重发` : '获取验证码' }}
            </button>
          </div>
          <p v-if="errors.emailCode" class="error-message">{{ errors.emailCode }}</p>
        </div>
      </form>

      <!-- 身份选择 -->
      <div class="identity-selector">
        <label class="form-label">身份选择</label>
        <div class="radio-group">
          <label class="radio-item">
            <input 
              type="radio" 
              name="identity" 
              value="buyer" 
              v-model="identity"
            >
            <span>买家</span>
          </label>
          <label class="radio-item">
            <input 
              type="radio" 
              name="identity" 
              value="merchant" 
              v-model="identity"
            >
            <span>商户</span>
          </label>
        </div>
      </div>

      <!-- 登录按钮 -->
      <button 
        class="login-btn" 
        @click="handleLogin"
        :disabled="isLoading"
      >
        <span v-if="!isLoading">登录</span>
        <span v-if="isLoading" class="loading">
          <i class="loading-icon"></i>登录中...
        </span>
      </button>

      <!-- 辅助链接 -->
      <div class="helper-links">
        <router-link to="/register" class="link-item">注册账号</router-link>
        <a href="javascript:;" class="link-item" @click="showForgotDialog = true">忘记密码</a>
      </div>
    </div>

    <!-- 忘记密码弹窗 -->
    <div class="dialog-mask" v-if="showForgotDialog">
      <div class="forgot-dialog">
        <div class="dialog-header">
          <h3>找回密码</h3>
          <button class="close-btn" @click="showForgotDialog = false">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label class="form-label">注册邮箱</label>
            <div class="input-wrapper">
              <i class="icon-email"></i>
              <input 
                type="email" 
                placeholder="请输入注册邮箱" 
                v-model="forgotForm.email"
              >
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">验证码</label>
            <div class="input-with-btn">
              <div class="input-wrapper">
                <i class="icon-code"></i>
                <input 
                  type="text" 
                  placeholder="请输入验证码" 
                  v-model="forgotForm.code"
                >
              </div>
              <button 
                type="button" 
                class="code-btn"
                :disabled="forgotCountdown > 0"
                @click="sendForgotCaptcha"
              >
                {{ forgotCountdown > 0 ? `${forgotCountdown}s后重发` : '获取验证码' }}
              </button>
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">新密码</label>
            <div class="input-wrapper">
              <i class="icon-lock"></i>
              <input 
                type="password" 
                placeholder="请设置新密码" 
                v-model="forgotForm.newPassword"
              >
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button 
            class="cancel-btn" 
            @click="showForgotDialog = false"
          >
            取消
          </button>
          <button class="confirm-btn" @click="confirmForgotPassword">
            确认重置
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserInfoStore } from '@/stores/userInfo';
import request from '@/utils/request'; // 统一使用封装的请求工具
import defaultAvatar from '@/assets/default.png'; // 声明导入的默认头像

// 路由实例
const router = useRouter();
const userStore = useUserInfoStore();

// 全局提示状态
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref('info');
const toastIcon = ref('');
const progressWidth = ref('100%');
let toastTimer = null;
let progressTimer = null;

// 登录状态管理
const loginType = ref('phone');
const identity = ref('buyer');
const isLoading = ref(false);
const showForgotDialog = ref(false);

// 表单数据
const phoneForm = ref({ phone: '', password: '' });
const emailForm = ref({ email: '', code: '' });
const forgotForm = ref({ email: '', code: '', newPassword: '' });

// 验证码倒计时
const emailCountdown = ref(0);
const forgotCountdown = ref(0);

// 错误提示
const errors = ref({
  phone: '',
  phonePassword: '',
  email: '',
  emailCode: ''
});

// 显示提示窗
const showToastMessage = (message, type = 'info', duration = 3000) => {
  if (toastTimer) clearTimeout(toastTimer);
  if (progressTimer) clearInterval(progressTimer);
  
  toastMessage.value = message;
  toastType.value = type;
  
  switch (type) {
    case 'success': toastIcon.value = '✅'; break;
    case 'error': toastIcon.value = '❌'; break;
    default: toastIcon.value = '💡';
  }
  
  showToast.value = true;
  progressWidth.value = '100%';
  
  toastTimer = setTimeout(hideToast, duration);
  const startTime = Date.now();
  progressTimer = setInterval(() => {
    const percentage = Math.max(0, 100 - ((Date.now() - startTime) / duration * 100));
    progressWidth.value = `${percentage}%`;
    if (percentage <= 0) clearInterval(progressTimer);
  }, 30);
};

// 隐藏提示窗
const hideToast = () => {
  showToast.value = false;
  clearTimeout(toastTimer);
  clearInterval(progressTimer);
};

// 切换登录方式
const switchLoginType = (type) => {
  loginType.value = type;
  Object.keys(errors.value).forEach(key => errors.value[key] = '');
};

// 清除错误提示
const clearError = (field) => {
  errors.value[field] = '';
};

// 手机号表单验证
const validatePhoneForm = () => {
  let isValid = true;
  const phoneReg = /^1[3-9]\d{9}$/;
  
  if (!phoneForm.value.phone.trim()) {
    errors.value.phone = '请输入手机号';
    isValid = false;
  } else if (!phoneReg.test(phoneForm.value.phone.trim())) {
    errors.value.phone = '请输入正确的手机号';
    isValid = false;
  }
  
  if (!phoneForm.value.password.trim()) {
    errors.value.phonePassword = '请输入密码';
    isValid = false;
  } else if (phoneForm.value.password.length < 6) {
    errors.value.phonePassword = '密码长度不能少于6位';
    isValid = false;
  }
  
  return isValid;
};

// 邮箱表单验证
const validateEmailForm = () => {
  let isValid = true;
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  
  if (!emailForm.value.email.trim()) {
    errors.value.email = '请输入邮箱';
    isValid = false;
  } else if (!emailReg.test(emailForm.value.email.trim())) {
    errors.value.email = '请输入正确的邮箱格式';
    isValid = false;
  }
  
  if (!emailForm.value.code.trim()) {
    errors.value.emailCode = '请输入验证码';
    isValid = false;
  }
  
  return isValid;
};

// 发送邮箱验证码
const sendEmailCaptcha = () => {
  const email = emailForm.value.email.trim();
  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    showToastMessage('请输入正确的邮箱', 'error');
    return;
  }

  request.get(`/api/captcha/sendCaptcha?email=${encodeURIComponent(email)}`)
    .then(res => {
      if (res.data === '验证码已发送') {
        showToastMessage('验证码已发送', 'success');
        startEmailCountdown();
      } else {
        showToastMessage('发送失败：' + res.data, 'error');
      }
    })
    .catch(() => showToastMessage('网络错误', 'error'));
};

// 发送忘记密码验证码
const sendForgotCaptcha = () => {
  const email = forgotForm.value.email.trim();
  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    showToastMessage('请输入正确的邮箱', 'error');
    return;
  }

  request.get(`/api/captcha/sendCaptcha?email=${encodeURIComponent(email)}`)
    .then(res => {
      if (res.data === '验证码已发送') {
        showToastMessage('验证码已发送', 'success');
        startForgotCountdown();
      } else {
        showToastMessage('发送失败：' + res.data, 'error');
      }
    })
    .catch(() => showToastMessage('网络错误', 'error'));
};

// 倒计时
const startEmailCountdown = () => {
  emailCountdown.value = 60;
  const timer = setInterval(() => {
    emailCountdown.value--;
    if (emailCountdown.value <= 0) clearInterval(timer);
  }, 1000);
};

const startForgotCountdown = () => {
  forgotCountdown.value = 60;
  const timer = setInterval(() => {
    forgotCountdown.value--;
    if (forgotCountdown.value <= 0) clearInterval(timer);
  }, 1000);
};


// 登录处理
const handleLogin = () => {
  console.log('开始执行登录逻辑'); // ① 确认进入登录方法

  if ((loginType.value === 'phone' && !validatePhoneForm()) || 
      (loginType.value === 'email' && !validateEmailForm())) {
    console.log('表单验证失败'); // ② 确认是否因表单验证失败退出
    return;
  }

  isLoading.value = true;
  const requestData = loginType.value === 'phone' 
    ? { 
        phone: phoneForm.value.phone.trim(), 
        password: phoneForm.value.password.trim(), 
        identity: identity.value 
      }
    : { 
        email: emailForm.value.email.trim(), 
        verificationCode: emailForm.value.code.trim(), 
        identity: identity.value 
      };


  // 使用封装的request
  request.post('/api/user-account/login', requestData)
    .then(res => {
      isLoading.value = false;

      if (res.data.code === '200') { 
        const userId = res.data.data.id || res.data.data.userId;
        if (!userId) {
          console.error('后端未返回用户ID！');
          showToastMessage('登录信息不完整', 'error');
          return;
        }

        localStorage.setItem('token', res.data.data.token)
        localStorage.setItem('userInfo', JSON.stringify({
            userId: userId,
            avatar: res.data.data.avatar,
            username: res.data.data.username
          }))
        // 保存用户信息
        const userInfo = { 
          ...res.data.data, 
          token : res.data.data.token,
          id: userId, // 强制赋值id
          identity: identity.value, 
          avatarUrl: res.data.data.avatar || defaultAvatar 
        };
        userStore.login(userInfo);
        console.log('用户信息保存成功:', userInfo);

        showToastMessage('登录成功，正在跳转...', 'success');
  
        // 跳转路径
        const redirectPath = identity.value === 'user' 
          ? '/'  
          : '/merchant';
        console.log('准备跳转路径:', redirectPath);
        
        // 立即跳转（去掉延迟，避免定时器问题）
        router.push(redirectPath).then(() => {
          console.log('跳转成功');
        }).catch(err => {
          console.log('跳转失败:', err);
        });
      } else {
        console.log('后端返回失败:', res.data.message);
        showToastMessage(res.data.message || '登录失败', 'error');
      }
    })
    .catch(err => {
      console.log('登录请求失败:', err);
      isLoading.value = false;
      showToastMessage('登录请求失败，请检查网络或接口', 'error');
    });
};
// 确认重置密码
const confirmForgotPassword = () => {
  if (!forgotForm.value.email.trim()) {
    showToastMessage('请输入注册邮箱', 'error');
    return;
  }
  if (!forgotForm.value.code.trim()) {
    showToastMessage('请输入验证码', 'error');
    return;
  }
  if (!forgotForm.value.newPassword.trim() || forgotForm.value.newPassword.length < 6) {
    showToastMessage('请设置6位以上的新密码', 'error');
    return;
  }

  // 接口路径补全/api
  request.post('/api/user-account/reset-password', {
    email: forgotForm.value.email.trim(),
    code: forgotForm.value.code.trim(),
    newPassword: forgotForm.value.newPassword.trim()
  })
    .then(response => {
      if (response.data.code === 200) {
        showToastMessage('密码重置成功，请使用新密码登录', 'success');
        showForgotDialog.value = false;
        forgotForm.value = { email: '', code: '', newPassword: '' };
        forgotCountdown.value = 0;
      } else {
        showToastMessage(response.data.msg || '密码重置失败，请重试', 'error');
      }
    })
    .catch(error => {
      showToastMessage(error.response?.data?.msg || '网络错误，请稍后重试', 'error');
    });
};
</script>


<style scoped>
/* 基础样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.login-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('https://picsum.photos/id/1060/1920/1080') no-repeat center;
  background-size: cover;
  opacity: 0.1;
  z-index: 0;
}

/* 登录卡片 */
.login-card {
  position: relative;
  width: 100%;
  max-width: 420px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  padding: 30px;
  z-index: 1;
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  color: #409eff;
  font-size: 28px;
  margin-bottom: 8px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

/* 登录方式切换 */
.login-type-tabs {
  display: flex;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
}

.login-type-tabs button {
  flex: 1;
  padding: 10px 0;
  background: transparent;
  border: none;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: color 0.3s;
}

.login-type-tabs button.active {
  color: #409eff;
  font-weight: 500;
}

.login-type-tabs button.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409eff;
}

/* 表单样式 */
.login-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.input-wrapper {
  position: relative;
}

.input-wrapper input {
  width: 100%;
  height: 44px;
  padding: 0 15px 0 40px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.input-wrapper input:focus {
  border-color: #409eff;
}

.input-wrapper i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
}

/* 图标样式 */
.icon-phone::before {
  content: "📞";
}

.icon-email::before {
  content: "✉️";
}

.icon-lock::before {
  content: "🔒";
}

.icon-code::before {
  content: "🔑";
}

.input-with-btn {
  display: flex;
  gap: 10px;
}

.input-with-btn .input-wrapper {
  flex: 1;
}

.code-btn {
  padding: 0 16px;
  height: 44px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 6px;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.code-btn:disabled {
  background-color: #eee;
  color: #999;
  cursor: not-allowed;
}

.code-btn:not(:disabled):hover {
  background-color: #eee;
}

.error-message {
  margin-top: 5px;
  color: #409eff;
  font-size: 12px;
}

/* 身份选择 */
.identity-selector {
  margin-bottom: 25px;
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-item input {
  margin-right: 6px;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 46px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #407cff;
}

.login-btn:disabled {
  background-color: #40a0ffa4;
  cursor: not-allowed;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.loading-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid #fff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 辅助链接 */
.helper-links {
  display: flex;
  justify-content: center;
  margin-top: 15px;
  gap: 20px;
}

.link-item {
  color: #409eff;
  font-size: 14px;
  text-decoration: none;
}

.link-item:hover {
  text-decoration: underline;
}

/* 忘记密码弹窗 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.forgot-dialog {
  width: 100%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: transparent;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.dialog-body {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  padding: 16px 20px;
  border-top: 1px solid #eee;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 40px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  color: #333;
}

.cancel-btn:hover {
  background-color: #eee;
}

.confirm-btn {
  background-color: #409eff;
  border: none;
  color: #fff;
}

.confirm-btn:hover {
  background-color: #2691fc;
}

/* 新增：全局提示悬浮窗样式 */
.toast {
  position: fixed;
  top: -50px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 20px;
  border-radius: 6px;
  color: white;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 2000;
  display: flex;
  flex-direction: column;
  min-width: 280px;
  max-width: 400px;
  transition: all 0.3s ease;
  opacity: 0;
}

.toast-show {
  top: 20px;
  opacity: 1;
}

.toast-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toast-error {
  background-color: #ff4d4f;
}

.toast-success {
  background-color: #52c41a;
}

.toast-info {
  background-color: #1890ff;
}

.toast-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 3px;
  background-color: rgba(255, 255, 255, 0.5);
  transition: width 0.3s linear;
}
</style>